#!/usr/bin/env python
# -*- coding:utf-8 -*-
from math import radians, cos, sin, asin, sqrt

import requests
import json
import config

GEO_URL = "http://restapi.amap.com"
KEY = "b86371c45b8a45ae5e53bfc3efb364ba"
mdb = config.mdb

def get_location(address):

    url = GEO_URL + '/v3/geocode/geo'
    param = {
        "key": KEY,
        "address": address
    }
    try:
        result = requests.get(url, param)
        result = json.loads(result.text)
        if result['geocodes'] and len(result['geocodes']) > 0:
            return result['geocodes'][0]
    except Exception as identifier:
        pass
    return {}


def loglat_2_location(longitude, latitude):
    """
    通过经纬度查询省市区
    https://restapi.amap.com/v3/geocode/regeo?parameters
    location
    :return:
    """
    url = "https://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s,%s" % (KEY, longitude, latitude)
    try:
        result = requests.get(url)
        result = json.loads(result.content)
        if result.get("regeocode") and len(result.get("regeocode")) > 0:
            return result["regeocode"]["addressComponent"]
    except Exception as e:
        pass
    return {}